/**
 * 
 * CONTROLLER OF ADJUST BAR
 * 
 * 2009-12-18
 * 
 * 
 * */
package com.components.adjustbar
{
	import com.components.button.MCButton;
	
	import core.section.Controller;
	
	import flash.display.DisplayObject;
	import flash.events.MouseEvent;
	
	[Event(name="change",type="com.components.adjustbar.AdjustBarEvents")]
	[Event(name="activate",type="com.components.adjustbar.AdjustBarEvents")]
	[Event(name="deactivate",type="com.components.adjustbar.AdjustBarEvents")]
	
	public class AdjustBar extends Controller
	{
		//START...
		
		
		//PORPERTY...	
		
		private var view:AdjustBarView;
		
		private var slider:MCButton;
		
		private var bar:MCButton;
		
		//CONSTRUCTOR...
		public function AdjustBar(target:DisplayObject)
		{
			
			super(target);
			
			init();
			
		}
		
		//METHODS...
		
		// initializing..
		private function init():void
		{
			
			view = new AdjustBarView(target);
			
			slider = new MCButton(view.slider);
			
			bar = new MCButton(view.bar);
			
			configEventListeners();
			
		}
		
		// config event listeners...
		private function configEventListeners():void
		{
			
			bar.addEventListener(MouseEvent.MOUSE_DOWN,barMouseDownHandler);
			
		}
		
		// bar mouse down handler...
		private function barMouseDownHandler(evt:MouseEvent):void
		{
				
			view.barStartDrag();
			
			slider.state = MCButton.OVER_STATE;
															
			target.stage.addEventListener(MouseEvent.MOUSE_UP,stageMouseUpHandler);
			
			target.stage.addEventListener(MouseEvent.MOUSE_MOVE,stageMouseMoveHandler);
			
			dispatchEvent( new AdjustBarEvents(AdjustBarEvents.ACTIVATE));
			
		}
		
		// stage mouse up handler...
		private function stageMouseUpHandler(evt:MouseEvent):void
		{
			
			view.barStopDrag();
			
			slider.state = MCButton.OUT_STATE;
			
			target.stage.removeEventListener(MouseEvent.MOUSE_UP,stageMouseUpHandler);
			
			target.stage.removeEventListener(MouseEvent.MOUSE_MOVE,stageMouseMoveHandler);
			
			dispatchEvent(new AdjustBarEvents(AdjustBarEvents.DEACTIVATE));
			
		}
		
		// stage mouse move handler...
		private function stageMouseMoveHandler(evt:MouseEvent):void
		{
			
			dispatchEvent(new AdjustBarEvents(AdjustBarEvents.CHANGE,percent));
			
		}
		
		//set percent...
		public function set percent(val:Number):void
		{
			
			val = val > 1 ? 1 : val;
			
			val = val < 0 ? 0 : val;
			
			view.setBarPosition(val);
						
		}
		
		// get percent...
		public function get percent():Number
		{
			
			return (bar.target.x - slider.target.x ) / (slider.target.width - bar.target.width);
			
		}
		
		
		//END...
	}
}